package com.heima.kafka.sample;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Properties;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-11-17 10:23
 */
public class ConsumerQuickStart109 {

    public static void main(String[] args) {

        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        //消费者组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"test2");

        //创建消费者对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
        //添加订阅的topic主题
        ArrayList<String> strings = new ArrayList<>();
        strings.add("stream109_dest");
        consumer.subscribe(strings);
        //消费数据
        while(true){
            //最多等1秒钟，如果没数据，返回了
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofSeconds(1));
            for (ConsumerRecord<String, String> msg : poll) {
                System.out.println(msg.key() + msg.value());
            }
        }

    }
}
